import React, { FC, useState, useEffect } from 'react';
import { FetchUpdateCount, FetchDeleteCartItem, FetchCartList, FetchTotalPrice  } from '../../api'
import { Button } from 'antd'

// 引用类型的直接赋值设置
// 基本类型的直接赋值设置 有什么区别？

const TotalPrice:FC<any> = (props) => {
   return <h1>
     {props.totalPrice}
   </h1>
}

const Cart = () => {
  const [state, setstate] = useState<any[]>([])
  const [totalPrice, setTotalPrice] = useState<any>(0)

  useEffect(() => {
    getCartGoods({})
    handleTotalPrice()
  }, [])

  //
  const getCartGoods = async ({page=0, size=5}: {page?: number, size?: number}) => {
    // ++ --
    const data = await FetchCartList({page, size})
    console.log('data....:', data)
    // setstate(data.data)
    // setstate([...data.data])
    setstate(state => [...data.data]) // 如果不拷贝会出现什么情况
  }

  const handleAddItem = async ({skuCount, skuId}: {skuCount: number, skuId: string}) => {
    const data = await FetchUpdateCount({skuCount: skuCount + 1, skuId})
    getCartGoods({})
    handleTotalPrice()

  }

  const handleRemoveItem = async ({skuCount, skuId}: {skuCount: number, skuId: string}) => {
    if(skuCount<=1) {
      // 删除
      if(window.confirm('确定删除吗？')) {
         // 调用删除购物车列表接口
         console.log('确定删除吗？')
         const deleteData = await FetchDeleteCartItem({skuId})
         // 判断删除成功，然后调用 列表接口
         getCartGoods({})
         handleTotalPrice()
      }
      return;
   }
    const data = await FetchUpdateCount({skuCount: skuCount - 1, skuId})
    console.log('data:/......:',data)
    getCartGoods({})
    handleTotalPrice()
  }

  const handleTotalPrice = async () => {
    const data = await FetchTotalPrice()
    setTotalPrice(data.data.totalPrice)
    console.log('data, ....:', data.data.totalPrice)
  }

  return <div>
    {
      state.map(item => {
        return <div key={item.id}>
          {item.skuId} :
          {item.imgurl} :

         <Button onClick={() => handleAddItem({skuCount: item.skuCount,skuId: item.skuId})}>+</Button>
         <span>  {item.skuCount}</span>
         <Button onClick={() => handleRemoveItem({skuCount: item.skuCount,skuId: item.skuId})}>-</Button>
          <hr/>
        </div>
      })
    }
    <TotalPrice totalPrice={totalPrice}></TotalPrice>
  </div>
}

export default Cart;